/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.managecontrollers;

import classes.HibernateUtil;
import dao.QuizAnswersDao;
import dao.QuizDao;
import dao.QuizQuestionsDao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Answers;
import models.Quiz;
import models.Quizquestion;

/**
 * This Controller manages the add,edit and remove for a question with the
 * answers.
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class ManageQuizQuestionController extends HttpServlet {

    /**
     * This do get method checks if it has to remove,edit or add a question.
     * Depending on the method it redirects to a different page and sets the
     * right objects for it.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("idremove") != null) {
            removeQuizQuestion(Long.parseLong(request.getParameter("idremove")), request, response);
        } else if (request.getParameter("idedit") != null) {
            editQuizQuestion(Long.parseLong(request.getParameter("idedit")), request, response);
        } else {
            manageQuizQuestion(request, response);
        }
    }

    /**
     * Do post method it checks if it has to edit or add a question. Calls the
     * right method with it.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("formoption").equalsIgnoreCase("Questionedit")) {
            postEdit(Long.parseLong(request.getParameter("qid")), request, response);
        } else {
            postAdd(request, response);
        }
    }

    /*
     * method to remove a question.
     * redirects back to the question page.
     */
    private void removeQuizQuestion(long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //Connection with database using Dao
        HibernateUtil hu = new HibernateUtil();
        QuizQuestionsDao qd = new QuizQuestionsDao(hu.openSession());
        QuizAnswersDao qad = new QuizAnswersDao(hu.openSession());

        //gets the quizid and question
        long quizid = qd.get(id).getQuiz().getId();
        Quizquestion question = qd.get(id);

        //Deletes all answers linked to the question
        for (Answers a : qad.findAllbyQuestion(id)) {
            qad.delete(a);
        }

        //deletes question
        qd.delete(qd.get(id));

        //Sets the right order for the other questions.
        int count = 1;
        for (Quizquestion q : qd.findAllbyQuiz(quizid)) {
            q.setOrder(count);
            qd.save(q);
            count++;
        }


        hu.close();

        response.sendRedirect("QuizQuestion?quizid=" + quizid);
    }

    /*
     * Method to set objects to the add edit form to be edited.
     * redirects to the add/edit questionpage
     */
    private void editQuizQuestion(long parseLong, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Connection to the database using Daos
        HibernateUtil hu = new HibernateUtil();
        QuizQuestionsDao qqd = new QuizQuestionsDao(hu.openSession());
        QuizAnswersDao qad = new QuizAnswersDao(hu.openSession());

        //gets the questionid to get the question from
        long questionid = Long.parseLong(request.getParameter("idedit"));

        // gets the quiz and question
        Quiz quiz = qqd.get(questionid).getQuiz();
        Quizquestion question = qqd.get(questionid);

        //gets all the answers linked to the question
        List<Answers> alist = qad.findAllbyQuestion(questionid);

        hu.close();

        //sets all the values to be displayed in the form
        request.setAttribute("Questionedit", question);
        request.setAttribute("Option1", alist.get(0));
        request.setAttribute("Option2", alist.get(1));
        request.setAttribute("Option3", alist.get(2));
        request.setAttribute("Option4", alist.get(3));
        request.setAttribute("quiz", quiz);

        RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_quizquestion.jsp");
        dispatcher.forward(request, response);
    }

    /*
     * redirects to the add edit to add a question.
     * sets the quiz object.
     */
    private void manageQuizQuestion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long quizid = Long.parseLong(request.getParameter("quizid"));

        HibernateUtil hu = new HibernateUtil();
        QuizDao qd = new QuizDao(hu.openSession());

        Quiz quiz = qd.get(quizid);

        request.setAttribute("quiz", quiz);

        RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_quizquestion.jsp");
        dispatcher.forward(request, response);

    }

    /*
     * Method to save the edited question
     * Redirects to the question page.
     */
    private void postEdit(long parseLong, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //gets values form the form
        String name = request.getParameter("name");
        long id = Long.parseLong(request.getParameter("quizid"));
        String option1 = request.getParameter("option1");
        String option2 = request.getParameter("option2");
        String option3 = request.getParameter("option3");
        String option4 = request.getParameter("option4");
        String explanation = request.getParameter("explanation");
        String correct = request.getParameter("correct");

        //connection to the database using Dao
        HibernateUtil hu = new HibernateUtil();
        QuizQuestionsDao qqd = new QuizQuestionsDao(hu.openSession());
        QuizDao qd = new QuizDao(hu.openSession());
        QuizAnswersDao qad = new QuizAnswersDao(hu.openSession());

        //gets the quiz and question from the database
        Quiz quiz = qd.get(id);
        Quizquestion question = qqd.get(Long.parseLong(request.getParameter("qid")));

        //sets(edit) the question and explanation
        question.setName(name);
        question.setExplanation(explanation);
        qqd.update(question);//updates the question

        //gets all answers linked with the question
        ArrayList<Answers> answers = (ArrayList<Answers>) qad.findAllbyQuestion(question.getId());

        //edits the question using the values from the form
        answers.get(0).setCorrect(correct.equals("1"));
        answers.get(0).setValue(option1);
        answers.get(1).setCorrect(correct.equals("2"));
        answers.get(1).setValue(option2);
        answers.get(2).setCorrect(correct.equals("3"));
        answers.get(2).setValue(option3);
        answers.get(3).setCorrect(correct.equals("4"));
        answers.get(3).setValue(option4);

        //updates the answers
        for (Answers answer : answers) {
            qad.update(answer);
        }

        hu.close();



        response.sendRedirect("QuizQuestion?quizid=" + quiz.getId());
    }

    /*
     * method to add a question
     * redirects to the question page
     */
    private void postAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //gets the values fromt he form
        String name = request.getParameter("name");
        long id = Long.parseLong(request.getParameter("quizid"));
        String option1 = request.getParameter("option1");
        String option2 = request.getParameter("option2");
        String option3 = request.getParameter("option3");
        String option4 = request.getParameter("option4");
        String explanation = request.getParameter("explanation");
        String correct = request.getParameter("correct");

        //connection with the database using Dao
        HibernateUtil hu = new HibernateUtil();
        QuizQuestionsDao qqd = new QuizQuestionsDao(hu.openSession());
        QuizDao qd = new QuizDao(hu.openSession());
        QuizAnswersDao qad = new QuizAnswersDao(hu.openSession());

        //gets the quiz and initializes question
        Quiz quiz = qd.get(id);
        Quizquestion question;

        //gets all the questions and sets the ordernumber for the new question
        ArrayList<Quizquestion> questions = (ArrayList<Quizquestion>) qqd.findAllbyQuiz(quiz.getId());
        int ordernr = questions.size() + 1, count = 1;

        //if there is a missing orderid the question will replace the missing order
        // for example if there are 2 questions with order id 1 and 3 the new question will have 2.
        for (Quizquestion q : questions) {
            if (q.getOrder() != count) {
                ordernr = count;
                break;
            }
            count++;
        }

        //makes the question object and saves it.
        question = new Quizquestion(0, ordernr, quiz, name, explanation);
        qqd.save(question);

        //gets the list of questions to get the question that has just been added.
        ArrayList<Quizquestion> a = (ArrayList<Quizquestion>) qqd.findAllbyQuiz(quiz.getId());
        question = a.get(a.size() - 1);

        //saves all the answers.
        qad.save(new Answers(0, option1, correct.equals("1"), question));
        qad.save(new Answers(0, option2, correct.equals("2"), question));
        qad.save(new Answers(0, option3, correct.equals("3"), question));
        qad.save(new Answers(0, option4, correct.equals("4"), question));


        hu.close();



        response.sendRedirect("QuizQuestion?quizid=" + quiz.getId());
    }
}
